package com.zsh.wanandroid.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.dxq.basic_ui_library.loadSirCallBack.EmptyCallback;
import com.dxq.basic_ui_library.loadSirCallBack.ErrorCallback;
import com.dxq.basic_ui_library.loadSirCallBack.LoadingCallback;
import com.dxq.basic_ui_library.manager.RecyclerViewLinearLayoutManager;
import com.zsh.wanandroid.R;
import com.zsh.wanandroid.api.ApiService;
import com.zsh.wanandroid.base.BaseActivity;
import com.zsh.wanandroid.base.BasePagerFragment;
import com.zsh.wanandroid.bean.ArticleBean;
import com.zsh.wanandroid.bean.ArticleTags;
import com.zsh.wanandroid.bean.BaseResult;
import com.zsh.wanandroid.bean.NavigationBean;
import com.zsh.wanandroid.http.ApiRequest;
import com.zsh.wanandroid.ui.activity.ArticleActivity;
import com.zsh.wanandroid.ui.adapter.NavigationRightAdapter;
import com.zsh.wanandroid.utils.UIUtils;

import java.io.Serializable;
import java.util.List;

import q.rorbin.verticaltablayout.VerticalTabLayout;
import q.rorbin.verticaltablayout.adapter.TabAdapter;
import q.rorbin.verticaltablayout.widget.ITabView;
import q.rorbin.verticaltablayout.widget.TabView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author zsh
 * @date 2020/3/19.
 * 功能：
 */

public class SystemPager2Fragment extends BasePagerFragment {

    private VerticalTabLayout verticalTabLayoutLeft;
    private RecyclerView recyclerViewRight;
    private NavigationRightAdapter rightAdapter;
    private List<NavigationBean<ArticleBean<ArticleTags>>> data;

    private final static int DEFAULT_PAGE = 1;//默认加载第1页

    public static SystemPager2Fragment newInstance(Bundle bundle) {
        SystemPager2Fragment fragment = new SystemPager2Fragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        if (null != arguments) {
        }
    }

    @Override
    protected int onCreateFragmentView() {
        return R.layout.system_navigation;
    }

    @Override
    protected void initView(View view) {
        verticalTabLayoutLeft = (VerticalTabLayout) view.findViewById(R.id.verticalTabLayout);
        recyclerViewRight = (RecyclerView) view.findViewById(R.id.recyclerViewRight);
        //recyclerViewRight.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerViewRight.setLayoutManager(new RecyclerViewLinearLayoutManager(getContext()));
        rightAdapter = new NavigationRightAdapter(R.layout.nav_right_item);
        recyclerViewRight.setAdapter(rightAdapter);

        rightAdapter.setAdapterItemClickListener(new NavigationRightAdapter.AdapterItemClickListener() {
            @Override
            public void onItemClick(NavigationBean<ArticleBean<ArticleTags>> item, int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("data", (Serializable) item.getArticles().get(position));
                BaseActivity activity = (BaseActivity) getActivity();
                activity.startActivity(ArticleActivity.class, bundle);
                UIUtils.showToast(item.getArticles().get(position).getTitle());
            }
        });
    }

    @Override
    protected void loadNet() {
        //获取导航数据
        ApiService apiService = ApiRequest.getInstance(getContext()).create(ApiService.class);
        apiService.getNavigationList().enqueue(new Callback<BaseResult<List<NavigationBean<ArticleBean<ArticleTags>>>>>() {
            @Override
            public void onResponse(Call<BaseResult<List<NavigationBean<ArticleBean<ArticleTags>>>>> call,
                                   Response<BaseResult<List<NavigationBean<ArticleBean<ArticleTags>>>>> response) {
                BaseResult<List<NavigationBean<ArticleBean<ArticleTags>>>> body = response.body();
                if (null == body) {
                    mBaseLoadService.showCallback(EmptyCallback.class);
                    return;
                }
                 data = body.getData();
                if (null != data && data.size() > 0) {
                    mBaseLoadService.showSuccess();
                    initLeftMenu(data);
                    //右侧设置数据
                    initRightContent(data);
                } else {
                    mBaseLoadService.showCallback(EmptyCallback.class);
                }
            }

            @Override
            public void onFailure(Call<BaseResult<List<NavigationBean<ArticleBean<ArticleTags>>>>> call, Throwable t) {
                mBaseLoadService.showCallback(ErrorCallback.class);
            }
        });
    }

    @Override
    protected void onNetReload(View v) {
        mBaseLoadService.showCallback(LoadingCallback.class);
        loadNet();
    }

    /**
     * 初始化左侧菜单栏
     * @param data
     */
    private void initLeftMenu(final List<NavigationBean<ArticleBean<ArticleTags>>> data) {

        verticalTabLayoutLeft.setTabAdapter(new TabAdapter() {
            @Override
            public int getCount() {
                return data.size();
            }

            @Override
            public ITabView.TabBadge getBadge(int position) {
                return null;
            }

            @Override
            public ITabView.TabIcon getIcon(int position) {
                return null;
            }

            @Override
            public ITabView.TabTitle getTitle(int position) {
                ITabView.TabTitle build = new ITabView.TabTitle.Builder().setContent(data.get(position).getName()).build();
                return build;
            }

            @Override
            public int getBackground(int position) {
                return R.color.colorWhite;//选中的背景颜色
            }
        });

        verticalTabLayoutLeft.setIndicatorColor(R.color.colorTheme2);
        verticalTabLayoutLeft.addOnTabSelectedListener(new VerticalTabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabView tab, int position) {
                tab.setBackgroundColor(getResources().getColor(R.color.colorWhite));
                //recyclerViewRight.move(position);
                //moveToPosition((LinearLayoutManager) recyclerViewRight.getLayoutManager(), recyclerViewRight, position);
                smoothMoveToPosition(recyclerViewRight, position);
            }

            @Override
            public void onTabReselected(TabView tab, int position) {

            }
        });
    }

    private void initRightContent(List<NavigationBean<ArticleBean<ArticleTags>>> data) {
        rightAdapter.replaceData(data);
    }

    /**
     * RecyclerView 移动到当前位置
     * @param manager 设置RecyclerView对应的manager
     * @param mRecyclerView 当前的RecyclerView
     * @param n 要跳转的位置
     */
    private void moveToPosition(LinearLayoutManager manager, RecyclerView mRecyclerView, int n) {
        int firstItem = manager.findFirstVisibleItemPosition();
        int lastItem = manager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            mRecyclerView.scrollToPosition(n);
        } else if (n <= lastItem) {
            int top = mRecyclerView.getChildAt(n - firstItem).getTop();
            mRecyclerView.scrollBy(0, top);
        } else {
            mRecyclerView.scrollToPosition(n);
        }

    }

    /**
     * 目标项是否在最后一个可见项之后
     */
    private boolean mShouldScroll;
    /**
     * 记录目标项位置
     */
    private int mToPosition;

    /**
     * 滑动到指定位置
     * @param mRecyclerView
     * @param position
     */
    private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));

        if (position < firstItem) {
            // 如果跳转位置在第一个可见位置之前，就smoothScrollToPosition可以直接跳转
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            // 跳转位置在第一个可见项之后，最后一个可见项之前
            // smoothScrollToPosition根本不会动，此时调用smoothScrollBy来滑动到指定位置
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();
                mRecyclerView.smoothScrollBy(0, top);
            }
        } else {
            // 如果要跳转的位置在最后可见项之后，则先调用smoothScrollToPosition将要跳转的位置滚动到可见位置
            // 再通过onScrollStateChanged控制再次调用smoothMoveToPosition，执行上一个判断中的方法
            mRecyclerView.smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }
    }
}
